<?php
/*
 * @Author: 哲学家乔布斯 <wuyangii@qq.com>
 * @Date: 2022-10-20 21:41:37
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-11-07 22:37:15
 * @Descripttion: 商品管理
 */
namespace app\admin\controller\system;
use think\Db;
class AgentOrder extends \app\admin\controller\Common
{
    public function index(){
    
        return view();
    }

    public function list(){
        $limit = request()->param('limit') ?? 15;
        $page = request()->param('page');
        $page = $page ? ($page - 1) * $limit : 0;
        $search = request()->param();
        $query = (new \app\common\model\AgentOrder())->where(1,1);
        isset($search['goods_title']) && $search['goods_title'] != "" ? $query->where("title like '%{$search['goods_title']}%'") : '';
        $query->order("id desc");

        $list = $query->limit($page, $limit)->append(['addtime_text','state_text'])->select();
        $count = $query->count();
        return self::successResult('',$list,$count);
    }

   public function info(){
        $id = request()->param('id');
        $info = (new \app\common\model\AgentOrder())
                    ->where(['id' => $id])
                    ->append(['addtime_text'])
                    ->find();
        $this->assign("info",$info);
        return view();
   }
   public function add(){
     
        if (request()->isPost()) {
            $id = request()->param('id');
            $state = request()->param('state');
            $admin_remarks = request()->param('admin_remarks');
            #查询订单是否存在
            $order = (new \app\common\model\AgentOrder())->where(['id' => $id])->find();
            if($order['state'] != 0){
                return self::errorResult("订单已经处理完成");
            }
            Db::startTrans();
            try{
                $message = "订单创建失败,请重试";
                $process = true;
              
                $sku = (new \app\common\model\GoodsSku())->where(['id' => $order['goods_sku_id']])->find();
                #查询商品是否存在
                $agent_goods_sku = (new \app\common\model\AgentGoodsSku())->where([
                    'goods_id' => $order['goods_id'],
                    'goods_sku_id' => $order['goods_sku_id'],
                    'agent_id' => $order['agent_id'],
                ])->find();
                if(!$agent_goods_sku && $state == 1){
                    $row = (new \app\common\model\AgentGoodsSku())->insertGetId([
                        'goods_id' => $sku['goods_id'],
                        'goods_sku_id' => $sku['id'],
                        'money_cost' => $sku['money'],
                        'stock' => $order['num'],
                        'agent_id' => $order['agent_id'],
                    ]);
                    if(!$row){
                        $message = "添加商品失败";
                        $process = false;
                    }
                }else if($state == 1){
                    $row = (new \app\common\model\AgentGoodsSku())->where([
                        'stock' => $agent_goods_sku['stock'],
                    ])->update([
                        'stock' => $agent_goods_sku['stock']+$order['num'],
                    ]);
                    if(!$row){
                        $message = "修改商品库存失败";
                        $process = false;
                    }
                }

                $row = (new \app\common\model\AgentOrder())->where(['id' => $id])->update([
                        'state' => $state,
                        'admin_id' => $this->userInfo['id'],
                        'admin_remarks' => $admin_remarks
                ]);
                if(!$row){
                    $message = "修改订单失败";
                    $process = false;
                }
                if ($process !== false) {
                    Db::commit(); // 提交事务
                } else {
                    Db::rollback(); // 回滚事务
                }

            } catch (\Exception $e) {
                $process = false;
                $message = $e->getMessage();
                Db::rollback(); // 回滚事务
            }
            if ($process !== false) {
                return self::successResult("创建成功");
            } else {
                return self::errorResult($message);
            }
        
    
        } else {
            $cate = (new \app\common\model\GoodsCate())->lists();
            $this->assign("cate",$cate);

            return view();
            }

    }
   public function goods(){
        $limit = request()->param('limit') ?? 15;
        $page = request()->param('page');
        $page = $page ? ($page - 1) * $limit : 0;
        $search = request()->param();
    
        $query = (new \app\common\model\Goods())->where(['is_del' => 0]);

        isset($search['goods_title']) && $search['goods_title'] != "" ? $query->where("title like '%{$search['goods_title']}%'") : '';
        $query->order("id desc");
        $where = [];
        if(!empty($search['bus_id'])){
            $where['bus_id'] = $search['bus_id'];
        }
        $list = $query->limit($page, $limit)->where($where)->append(['cate_title'])->select();
        $count = $query->count();
        return self::successResult('',$list,$count);
    }
        
   public function goods_sku(){
        $limit = request()->param('limit') ?? 15;
        $page = request()->param('page');
        $page = $page ? ($page - 1) * $limit : 0;
        $search = request()->param();
        $query = (new \app\common\model\GoodsSku())
                ->alias("goods_sku")
                ->join("{$this->tdb}goods goods","goods.id = goods_sku.goods_id")
                ->field([
                    'goods_sku.id',
                    'goods_sku.money',
                    'goods_sku.sku_title',
                    'goods.img',
                    'goods.title',
                    'goods.introduce',
                    'goods.cate_id',
                    ])
                ->where(['is_del' => 0]);
        isset($search['title']) && $search['title'] != "" ? $query->where("title like '%{$search['title']}%'") : '';
        $query->order("goods_sku.id desc");
        $where = [];
        if(!empty($search['bus_id'])){
            $where['bus_id'] = $search['bus_id'];
        }
        $list = $query->limit($page, $limit)->where($where)
                ->append(['cate_title'])
                ->select();
        $count = $query->count();
        return self::successResult('',$list,$count);
}

   public function delete(){
        $id = request()->param('id');
        if (empty($id)) $this->error("请选择要删除的数据");
        $table = new \app\common\model\Goods();
        if (is_array($id)) {
            $id = implode(",", $id);
            $row = $table->whereIn('id', $id)->update(['is_del' => 1]);
        } else {
            $row = $table->where('id', $id)->update(['is_del' => 1]);
        }
        return $row ? self::successResult("成功") : self::errorResult("失败");
   }
  
   public function is_index()
   {
       $id = request()->param('id');
       $is_index = request()->param('is_index');
       if (empty($id)) $this->error("请选择要修改的数据");
       $table = new \app\common\model\Goods();
       $row = $table->where('id', $id)->update(['is_index' => $is_index]);
       return $row ? self::successResult() : self::errorResult('操作失败!请刷新后重试！');
   }
 
}
